#!/bin/bash
# 安装Nginx及配置服务

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_nginx() {
    local appname="nginx-${Version}${NGINX_NAME_END}"
    local link="${NGINX_NAME}${Version}${NGINX_NAME_END}"
    
    if [ ! -e "${APPS_HOME}/${appname}" ];then
        echo "正在下载Nginx ${Version}..."
        wget -P ${APPS_HOME} $link
        if [ $? -ne 0 ]; then
            error_exit "Nginx下载失败"
        fi
    fi
    
    # 卸载已安装的nginx
    rpm -qa |grep nginx | xargs rpm -e --nodeps 2>/dev/null
    
    rpm -ivh ${APPS_HOME}/${appname}
    if [ $? -eq 0 ];then
        success_msg "nginx ${Version} 安装成功"
    else
        error_exit "nginx安装失败"
    fi
}

function configure_nginx_service() {
    if [[ ! -f "${NGINX_SERVICE}" ]];then
        echo "创建nginx服务文件"
        cat > ${NGINX_SERVICE} <<EOF
[Unit]
Description=nginx_server
Documentation=http://nginx.org/en/docs
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t -c /etc/nginx/nginx.conf
ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/usr/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

        systemctl daemon-reload
        systemctl start nginx
        systemctl enable nginx
        success_msg "Nginx服务配置完成"
    else
        echo "nginx服务文件已存在"
    fi
}

echo "开始安装Nginx..."

read -p "输入需要的nginx版本(默认1.20.2): " Version
if [ -z "${Version}" ];then
    Version="1.20.2"
    echo "使用默认版本: $Version"
fi

install_nginx
configure_nginx_service
